<template>
  <el-form
    ref="ruleFormRef"
    style="width: calc(100% - 20px)"
    :model="ruleForm"
    :rules="rules"
    label-width="120px"
    :disabled="isDetail"
  >
    <el-form-item label="活动名称" prop="name">
      <el-input v-model="ruleForm.name" placeholder="请输入活动名称" />
    </el-form-item>

    <el-form-item label="活动时间范围" prop="timeRange">
      <el-date-picker
        v-model="ruleForm.timeRange"
        type="datetimerange"
        range-separator="至"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
        value-format="YYYY-MM-DD HH:mm:ss"
        style="width: 100%"
        @change="handleTimeRangeChange"
      />
    </el-form-item>

    <el-form-item label="生效标准" prop="effectiveStandard">
      <el-select v-model="ruleForm.effectiveStandard" placeholder="请选择生效标准">
        <el-option label="付款后" :value="0" />
        <el-option label="订单完成" :value="1" />
      </el-select>
    </el-form-item>

    <el-form-item label="状态" prop="status">
      <el-select v-model="ruleForm.status" placeholder="请选择状态">
        <el-option label="启用" :value="1" />
        <el-option label="禁用" :value="0" />
      </el-select>
    </el-form-item>

    <el-form-item label="分享文案" prop="shareScheme">
      <el-input
        v-model="ruleForm.shareScheme"
        type="textarea"
        :rows="3"
        placeholder="请输入分享文案"
      />
    </el-form-item>

    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="分享图片" prop="shareImage">
          <UploadImg v-model="ruleForm.shareImage" :disabled="isDetail" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="Banner图片" prop="bannerImage">
          <UploadImg v-model="ruleForm.bannerImage" :disabled="isDetail" />
        </el-form-item>
      </el-col>
    </el-row>

    <el-form-item label="H5路径" prop="h5Path">
      <el-input v-model="ruleForm.h5Path" readonly>
        <template #append>
          <el-button @click="copyToClipboard(ruleForm.h5Path, 'H5路径')">
            <el-icon><Document /></el-icon>
            复制
          </el-button>
        </template>
      </el-input>
    </el-form-item>

    <el-form-item label="小程序路径" prop="appletPath">
      <el-input v-model="ruleForm.appletPath" readonly>
        <template #append>
          <el-button @click="copyToClipboard(ruleForm.appletPath, '小程序路径')">
            <el-icon><Document /></el-icon>
            复制
          </el-button>
        </template>
      </el-input>
    </el-form-item>
    <el-button
      class="add-type-config-button"
      v-if="!isDetail"
      type="primary"
      @click="addTypeConfig"
      :disabled="isMaxActivityTypesReached"
    >
      添加规则配置
    </el-button>
    <div v-for="(typeConfig, index) in ruleForm.typeConfigs" :key="index" class="type-config-item">
      <el-card class="mb-4" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>规则配置 {{ index + 1 }}</span>
            <el-button v-if="!isDetail" type="danger" size="small" @click="removeTypeConfig(index)"
              >删除</el-button
            >
          </div>
        </template>

        <el-form-item label="活动类型" prop="activityType.type" :disabled="isDetail">
          <el-select
            v-model="typeConfig.activityType.type"
            placeholder="请选择活动类型"
            @change="handleActivityTypeChange(index)"
          >
            <el-option
              v-for="option in availableActivityTypes(index)"
              :key="option.value"
              :label="option.label"
              :value="option.value"
              :disabled="option.disabled"
            />
          </el-select>
        </el-form-item>

        <!-- 累计订单数 -->
        <template v-if="typeConfig.activityType.type === 1">
          <div v-for="(rule, ruleIndex) in typeConfig.rules" :key="ruleIndex" class="rule-item">
            累计订单数大于等于
            <el-input-number
              v-model="rule.threshold"
              :disabled="isDetail"
              :controls="false"
              :min="1"
              style="width: 100px"
            />
            单且每单大于等于
            <el-input-number
              v-model="rule.perOrderAmount"
              :disabled="isDetail"
              :controls="false"
              :min="0"
              style="width: 100px"
            />
            元，赠送
            <el-input-number
              v-model="rule.experience"
              :disabled="isDetail"
              :controls="false"
              :min="0"
              style="width: 100px"
            />
            经验值和
            <el-input-number
              v-model="rule.points"
              :disabled="isDetail"
              :controls="false"
              :min="0"
              style="width: 100px"
            />
            积分
            <el-button
              v-if="!isDetail && typeConfig.rules.length > 1"
              type="danger"
              size="small"
              @click="removeRule(index, ruleIndex)"
              style="margin-left: 10px"
              >删除规则</el-button
            >
          </div>
          <el-button
            v-if="!isDetail"
            type="primary"
            size="small"
            @click="addRule(index)"
            style="margin-top: 10px"
            >添加规则</el-button
          >
        </template>

        <!-- 累计成交金额 -->
        <template v-else-if="typeConfig.activityType.type === 2">
          <div v-for="(rule, ruleIndex) in typeConfig.rules" :key="ruleIndex" class="rule-item">
            累计成交金额大于等于
            <el-input-number
              v-model="rule.threshold"
              :disabled="isDetail"
              :controls="false"
              :min="0"
              style="width: 100px"
            />
            元，赠送
            <el-input-number
              v-model="rule.experience"
              :disabled="isDetail"
              :controls="false"
              :min="0"
              style="width: 100px"
            />
            经验值和
            <el-input-number
              v-model="rule.points"
              :disabled="isDetail"
              :controls="false"
              :min="0"
              style="width: 100px"
            />
            积分
            <el-button
              v-if="!isDetail && typeConfig.rules.length > 1"
              type="danger"
              size="small"
              @click="removeRule(index, ruleIndex)"
              style="margin-left: 10px"
              >删除规则</el-button
            >
          </div>
          <el-button
            v-if="!isDetail"
            type="primary"
            size="small"
            @click="addRule(index)"
            style="margin-top: 10px"
            >添加规则</el-button
          >
        </template>

        <!-- 一次性充值金额 -->
        <template v-else-if="typeConfig.activityType.type === 3">
          <div v-for="(rule, ruleIndex) in typeConfig.rules" :key="ruleIndex" class="rule-item">
            一次性充值金额大于等于
            <el-input-number
              v-model="rule.threshold"
              :disabled="isDetail"
              :controls="false"
              :min="0"
              style="width: 100px"
            />
            元，赠送
            <el-input-number
              v-model="rule.experience"
              :disabled="isDetail"
              :controls="false"
              :min="0"
              style="width: 100px"
            />
            经验值和
            <el-input-number
              v-model="rule.points"
              :disabled="isDetail"
              :controls="false"
              :min="0"
              style="width: 100px"
            />
            积分
            <el-button
              v-if="!isDetail && typeConfig.rules.length > 1"
              type="danger"
              size="small"
              @click="removeRule(index, ruleIndex)"
              style="margin-left: 10px"
              >删除规则</el-button
            >
          </div>
          <el-button
            v-if="!isDetail"
            type="primary"
            size="small"
            @click="addRule(index)"
            style="margin-top: 10px"
            >添加规则</el-button
          >
        </template>

        <!-- 购买指定商品 -->
        <template v-else-if="typeConfig.activityType.type === 4">
          <el-button
            v-if="!isDetail"
            type="primary"
            size="small"
            :disabled="isDetail"
            @click="openChooseGoods(index)"
            >选择商品</el-button
          >
          <BasicTable
            v-if="typeConfig.rules.length"
            :columns="goodsColumns"
            :datasource="typeConfig.rules"
            :pagination="false"
            :response-structure="{
              data: 'rules',
              total: 'total'
            }"
            @cell-value-change="onGoodsCellValueChange(index, $event)"
            style="margin-top: 16px"
          >
            <template #picUrl="{ record }">
              <el-image :src="record.row.picUrl" fit="cover" style="width: 60px; height: 60px" />
            </template>
            <template #experience="{ record }">
              <el-input-number
                v-model="record.row.experience"
                :disabled="isDetail"
                :controls="false"
                :min="0"
                style="width: 100px"
              />
            </template>
            <template #points="{ record }">
              <el-input-number
                v-model="record.row.points"
                :disabled="isDetail"
                :controls="false"
                :min="0"
                style="width: 100px"
              />
            </template>
          </BasicTable>
          <ChooseGoods
            v-model:visible="chooseGoodsVisible"
            :selectedGoods="allSelectedGoods"
            @confirm="handleGoodsSelected"
          />
        </template>
      </el-card>
    </div>

    <el-card shadow="hover" class="mt-4 ml-6">
      <el-form-item label="商品详情" prop="introduce">
        <Editor v-model:modelValue="ruleForm.introduce" height="400px" :readonly="isDetail" />
      </el-form-item>
    </el-card>
  </el-form>
</template>

<script setup lang="ts">
import { reactive, ref, nextTick, computed, watch } from 'vue'
import { UploadImg } from '@/components/UploadFile'
import { ElMessage } from 'element-plus'
import { Document } from '@element-plus/icons-vue'
import { BasicTable } from '@/components/BasicTable'
import { ChooseGoods } from '@/components/ChooseGoods'
import { Editor } from '@/components/Editor'
import type { FormInstance, FormRules } from 'element-plus'
import type { ActivityRequest, TypeConfig } from '@/types/member/activity'
import { goodsColumns } from './index.data'
import { formatDate } from '@/utils/formatTime'
interface RuleForm extends Omit<ActivityRequest, 'startTime' | 'endTime'> {
  modalType?: string
  startTime?: string | number
  endTime?: string | number
  timeRange?: any
}

const emit = defineEmits(['success'])
const props = defineProps({
  data: {
    type: Object,
    default: () => ({})
  }
})

const isDetail = computed(() => props.data.modalType === 'detail')

// 选择商品弹窗相关
const chooseGoodsVisible = ref(false)
const currentTypeConfigIndex = ref(-1)

// 存储原始数据中的商品（用于判断已选商品）
const originalSelectedGoods = ref<any[]>([])

// 计算所有已选商品（只包含原始数据，不包含当前会话新添加的）
const allSelectedGoods = computed(() => {
  return originalSelectedGoods.value
})
function openChooseGoods(index: number) {
  currentTypeConfigIndex.value = index
  chooseGoodsVisible.value = true
}
function handleGoodsSelected(selectedGoods: any[]) {
  if (!selectedGoods || selectedGoods.length === 0) {
    chooseGoodsVisible.value = false
    return
  }

  // 检查当前类型配置是否存在
  if (currentTypeConfigIndex.value < 0 || !ruleForm.typeConfigs[currentTypeConfigIndex.value]) {
    chooseGoodsVisible.value = false
    return
  }

  const rules = selectedGoods.map((good) => ({
    productId: good.id,
    picUrl: good.picUrl,
    name: good.name,
    price: good.price,
    marketPrice: good.marketPrice,
    experience: 0,
    points: 0
  }))

  console.log('handleGoodsSelected - 映射后的规则:', rules)
  console.log(
    'handleGoodsSelected - 添加前的规则数量:',
    ruleForm.typeConfigs[currentTypeConfigIndex.value].rules.length
  )

  // 确保 rules 数组存在
  if (!Array.isArray(ruleForm.typeConfigs[currentTypeConfigIndex.value].rules)) {
    ruleForm.typeConfigs[currentTypeConfigIndex.value].rules = []
  }

  // 使用push方法来确保响应式更新
  ruleForm.typeConfigs[currentTypeConfigIndex.value].rules.push(...rules)

  console.log(
    'handleGoodsSelected - 添加后的规则数量:',
    ruleForm.typeConfigs[currentTypeConfigIndex.value].rules.length
  )
  console.log(
    'handleGoodsSelected - 更新后的规则:',
    ruleForm.typeConfigs[currentTypeConfigIndex.value].rules
  )

  chooseGoodsVisible.value = false
}
function onGoodsCellValueChange(typeConfigIndex: number, { rowIndex, prop, value }: any) {
  ruleForm.typeConfigs[typeConfigIndex].rules[rowIndex][prop] = value
}

// 监听数据变化
watch(
  () => props.data,
  (newVal, oldVal) => {
    console.log('ModalForm - props.data 变化:', {
      newVal: newVal ? { ...newVal, typeConfigs: newVal.typeConfigs?.length || 0 } : null,
      oldVal: oldVal ? { ...oldVal, typeConfigs: oldVal.typeConfigs?.length || 0 } : null
    })

    nextTick(() => {
      resetForm()
      console.log('ModalForm - 接收到新数据:', newVal)

      if (newVal && (newVal.modalType === 'edit' || newVal.modalType === 'detail')) {
        // 深拷贝typeConfigs，避免引用问题
        const typeConfigs = newVal.typeConfigs ? JSON.parse(JSON.stringify(newVal.typeConfigs)) : []

        Object.assign(ruleForm, {
          id: newVal.id || undefined,
          name: newVal.name || '',
          startTime: newVal.startTime || '',
          endTime: newVal.endTime || '',
          effectiveStandard: newVal.effectiveStandard || 0,
          status: newVal.status ?? 0,
          shareScheme: newVal.shareScheme || '',
          shareImage: newVal.shareImage || '',
          bannerImage: newVal.bannerImage || '',
          h5Path: newVal.h5Path || '',
          appletPath: newVal.appletPath || '',
          typeConfigs: typeConfigs,
          introduce: newVal.introduce || '' // 商品详情富文本内容
        })

        console.log('ModalForm - 赋值后的ruleForm.typeConfigs长度:', ruleForm.typeConfigs.length)

        if (newVal.startTime && newVal.endTime) {
          ruleForm.timeRange = [formatDate(newVal.startTime), formatDate(newVal.endTime)]
        } else {
          ruleForm.timeRange = null
        }

        // 保存原始数据中的商品信息（用于判断已选商品）
        const originalGoods: any[] = []
        if (newVal.typeConfigs && Array.isArray(newVal.typeConfigs)) {
          newVal.typeConfigs.forEach((typeConfig: any) => {
            if (typeConfig.activityType?.type === 4 && Array.isArray(typeConfig.rules)) {
              originalGoods.push(...typeConfig.rules)
            }
          })
        }
        originalSelectedGoods.value = [...originalGoods] // 使用展开运算符避免引用
        console.log('ModalForm - 保存原始商品数据:', originalSelectedGoods.value.length, '个商品')
      } else {
        // 新增模式时清空原始商品数据
        originalSelectedGoods.value = []
        console.log('ModalForm - 新增模式，清空原始商品数据')
      }
    })
  },
  { immediate: true, deep: true }
)

const ruleFormRef = ref<FormInstance>()

// 处理时间范围变化
const handleTimeRangeChange = (value: [string, string] | null) => {
  ruleForm.timeRange = value
  if (value && value.length === 2) {
    ruleForm.startTime = new Date(value[0]).getTime()
    ruleForm.endTime = new Date(value[1]).getTime()
  } else {
    ruleForm.startTime = ''
    ruleForm.endTime = ''
  }
}
const ruleForm = reactive<RuleForm>({
  modalType: 'add',
  name: '',
  startTime: '',
  endTime: '',
  timeRange: null,
  effectiveStandard: 0,
  status: 0,
  shareScheme: '',
  shareImage: '',
  bannerImage: '',
  h5Path: '',
  appletPath: '',
  typeConfigs: [],
  introduce: '' // 商品详情富文本内容
})

const rules = reactive<FormRules<RuleForm>>({
  name: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
  timeRange: [
    { required: true, message: '请选择活动时间范围', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (value && value.length === 2) {
          const [startTime, endTime] = value
          if (new Date(endTime) <= new Date(startTime)) {
            callback(new Error('结束时间必须大于开始时间'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  effectiveStandard: [{ required: true, message: '请选择生效标准', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
  introduce: [{ required: true, message: '请输入商品详情', trigger: 'blur' }]
})

// 重置表单
const resetForm = () => {
  console.log('重置表单数据')

  // 完全重新赋值，确保没有引用残留
  Object.keys(ruleForm).forEach((key) => {
    delete (ruleForm as any)[key]
  })

  Object.assign(ruleForm, {
    id: undefined,
    name: '',
    startTime: '',
    endTime: '',
    timeRange: null,
    effectiveStandard: 0,
    status: 1,
    shareScheme: '',
    shareImage: '',
    bannerImage: '',
    h5Path: '',
    appletPath: '',
    typeConfigs: [],
    introduce: '' // 商品详情富文本内容
  })

  // 重置原始商品数据
  originalSelectedGoods.value = []

  // 重置选择商品相关状态
  chooseGoodsVisible.value = false
  currentTypeConfigIndex.value = -1

  console.log('表单重置完成，当前ruleForm:', JSON.stringify(ruleForm))

  if (props.data.modalType === 'add') {
    addTypeConfig()
  }
}

// 添加规则配置
const addTypeConfig = () => {
  // 如果已达到最大活动类型数量，则不允许添加
  if (isMaxActivityTypesReached.value) {
    ElMessage.warning('最多只能添加4种不同的活动类型')
    return
  }

  // 获取当前未使用的活动类型
  const usedTypes = ruleForm.typeConfigs.map((config) => config.activityType.type)
  const allTypes = [1, 2, 3, 4]
  const availableTypes = allTypes.filter((type) => !usedTypes.includes(type))

  // 如果没有可用的类型，则不允许添加
  if (availableTypes.length === 0) {
    ElMessage.warning('所有活动类型都已添加')
    return
  }

  // 使用第一个可用的类型
  const type = availableTypes[0]

  const newTypeConfig: TypeConfig = {
    activityType: {
      type,
      status: 1
    },
    rules: []
  }
  // type=1时，规则需有perOrderAmount
  if (type === 1) {
    newTypeConfig.rules?.push({
      threshold: 0,
      perOrderAmount: 0,
      points: 0,
      experience: 0,
      status: 1
    })
  } else if (type === 4) {
    // type=4时，规则结构见handleGoodsSelected
    newTypeConfig.rules = []
  } else {
    newTypeConfig.rules?.push({
      threshold: 0,
      points: 0,
      experience: 0,
      status: 1
    })
  }
  ruleForm.typeConfigs.push(newTypeConfig)
}

// 删除规则配置
const removeTypeConfig = (index: number) => {
  ruleForm.typeConfigs.splice(index, 1)
}

// 添加规则
const addRule = (typeConfigIndex: number) => {
  const type = ruleForm.typeConfigs[typeConfigIndex].activityType.type
  if (type === 1) {
    ruleForm.typeConfigs[typeConfigIndex].rules.push({
      threshold: 0,
      perOrderAmount: 0,
      points: 0,
      experience: 0,
      status: 1
    })
  } else {
    ruleForm.typeConfigs[typeConfigIndex].rules.push({
      threshold: 0,
      points: 0,
      experience: 0,
      status: 1
    })
  }
}

// 删除规则
const removeRule = (typeConfigIndex: number, ruleIndex: number) => {
  ruleForm.typeConfigs[typeConfigIndex].rules.splice(ruleIndex, 1)
}

// 复制到剪贴板
const copyToClipboard = async (text: string, label: string) => {
  if (!text) {
    ElMessage.warning(`${label}为空，无法复制`)
    return
  }
  try {
    await navigator.clipboard.writeText(text)
    ElMessage.success(`${label}已复制到剪贴板`)
  } catch (err) {
    const textArea = document.createElement('textarea')
    textArea.value = text
    document.body.appendChild(textArea)
    textArea.select()
    try {
      document.execCommand('copy')
      ElMessage.success(`${label}已复制到剪贴板`)
    } catch (fallbackErr) {
      ElMessage.error('复制失败，请手动复制')
    }
    document.body.removeChild(textArea)
  }
}

// 活动类型变化
const handleActivityTypeChange = (index: number) => {
  console.log('活动类型变化，清空规则数组，索引:', index)
  ruleForm.typeConfigs[index].rules = []
  console.log('当前ruleForm:', JSON.stringify(ruleForm, null, 2))
}

// 获取可用的活动类型选项
const availableActivityTypes = (index: number) => {
  // 所有活动类型选项
  const allTypes = [
    { label: '累计订单数', value: 1, disabled: false },
    { label: '累计成交金额', value: 2, disabled: false },
    { label: '一次性充值', value: 3, disabled: false },
    { label: '购买指定商品', value: 4, disabled: false }
  ]

  // 获取当前已选择的活动类型
  const usedTypes = ruleForm.typeConfigs
    .filter((_, i) => i !== index) // 排除当前正在编辑的配置
    .map((config) => config.activityType.type)

  // 标记已使用的类型为禁用
  return allTypes.map((type) => ({
    ...type,
    disabled: usedTypes.includes(type.value)
  }))
}

// 判断是否已达到最大活动类型数量
const isMaxActivityTypesReached = computed(() => {
  // 如果已有4种不同的活动类型，则达到最大值
  const uniqueTypes = new Set(ruleForm.typeConfigs.map((config) => config.activityType.type))
  return uniqueTypes.size >= 4 || ruleForm.typeConfigs.length >= 4
})

// 提交表单
const submitForm = () => {
  if (!ruleFormRef.value) return
  ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      const submitData = { ...ruleForm }
      delete submitData.modalType
      if (!submitData.typeConfigs || submitData.typeConfigs.length === 0) {
        ElMessage.warning('请至少添加一个规则配置')
        return
      }
      emit('success', submitData)
    } else {
      console.log('error submit!', fields)
    }
  })
}

defineExpose({ submitForm })
</script>

<style scoped lang="scss">
.type-config-item {
  margin-bottom: 16px;
  margin-top: 36px;
  padding-left: 26px;
}
.add-type-config-button {
  margin-left: 26px;
}
.rule-item {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 16px;
  margin-bottom: 16px;
  background-color: #fafafa;
  position: relative;
}
.rule-actions {
  margin-top: 12px;
  text-align: right;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.mb-4 {
  margin-bottom: 16px;
}
</style>
